<?php

/**

 * 发起工作流程
 * 
 * @access  public 
 * @author  zhangyingheng<zhang_yh@jsumt.com.cn> 
 */

namespace Index\Controller;

use Think\Controller;

class DiaryController extends BaseController {

    public function _initialize() {
        parent::_initialize();
        $this->title = '工作日志';
    }

    //后台首页
    public function index() {
        $num = M('diary')->where("USER_ID = '" . session('user_id') . "'")->count();
        $this->diaryCount = $num;

        $num = M('weekly')->where('user_id="' . session('user_id') . '"')->count();
        $this->weeklyCount = $num;

        $this->tmpUser = session('user_id');
        $this->display();
    }

    //新建工作日志
    public function addDiary() {
        if (IS_AJAX) {
            $data = I('post.');
            $data['TO_ALL'] = $data['TO_ALL'] ? 1 : 0;
            $data['SUBJECT'] = I('SUBJECT') . ' 日志';
            if ($data['id']) {
                $map['DIA_ID'] = $data['id'];
                $res = M('diary')->where($map)->save($data);
            } else {
                //添加diary表
                $cdata['SUBJECT'] = $data['SUBJECT'];
                $cdata['USER_ID'] = session('user_id');
                $cdata['CONTENT'] = $data['CONTENT'];
                $cdata['DIA_DATE'] = $data['DIA_DATE'] ? $data['DIA_DATE'] : date('Y-m-d');
                $cdata['DIA_TIME'] = $data['DIA_TIME'] ? $data['DIA_TIME'] : date('Y-m-d H:i:s');
                $cdata['TO_ALL'] = $data['TO_ALL'];
                $cdata['DIA_TYPE'] = $data['DIA_TYPE'];
                if ($data['undefined'])
                    $cdata['TO_ID'] = implode(',', $data['undefined']);
                $cdata['is_mobile'] = 1;
                $res = M('diary')->add($cdata);
            }

            if ($res !== false) {
                $return['info'] = '提交成功';
//                $return['url'] = U('lists');
            } else {
                $return['info'] = '提交失败';
            }
            $this->ajaxReturn($return);
        }

        $this->sub = date('Y-m-d') . ' ' . getChineseWeek(date('w'));
        $this->time = date('Y-m-d H:i:s');
        $this->display();
    }

    public function getDate() {
        $date = strtotime(I('date'));
        $newData = I('date') . ' ' . getChineseWeek(date('w', $date));
        $this->ajaxReturn($newData);
    }

    //日志列表
    public function lists() {
        //根据当前时间判断是否结束
//        $data = M('diary')->field('DIA_ID')->select();
        $limit = $this->limit;
//        $lists = $this->getDiaryData($limit,session('user_id'));
        $lists = M('diary')->field("DIA_ID,USER_ID,SUBJECT,CONTENT,DIA_DATE,READERS")->where("USER_ID = '" . session('user_id') . "'")->order("DIA_DATE DESC")->limit(0, $limit)->select();
        foreach ($lists as $key => $row) {
            $num_rows = M('diary_comment')->where('DIA_ID = ' . $row['dia_id'])->count();
            $lists[$key]['num_rows'] = $num_rows;
            if ($row['dia_date'] !== '0000-00-00') {
                $lists[$key]['dia_date'] = date('Y-m-d', strtotime($row['dia_date']));
            }
            $lists[$key]['content'] = mb_substr($row['content'], 0, 60, 'utf-8');
            $lists[$key]['user_name'] = getChineseName($row['user_id']);
            //截取日志日期
            if (is_numeric(substr($row['subject'], 0, 4))) {
                $subdate = msubstr($row['subject'], 0, 10, 'utf-8', false);
            }
            $lists[$key]['dia_date'] = $subdate ? $subdate : $row['dia_date'];
        }
        $this->lists = $lists;
        $this->session_user = session('user_id');
        $this->display();
    }

    /*
     * 获取日志列表
     * param $limit 取几条，空取全部
     * return array
     */

    private function getDiaryData($limit, $user_id) {
        $p = I('get.p', 1, 'intval');
        $start = $limit * ($p - 1);
        if ($limit) {
            $lists = M('diary')->field("DIA_ID,USER_ID,DIA_DATE,SUBJECT")->where("USER_ID = '" . $user_id . "'")->order('DIA_DATE desc')->limit($start, $limit)->select();
        } else {
            $lists = M('diary')->field("DIA_ID,USER_ID,DIA_DATE,SUBJECT")->where("USER_ID = '" . $user_id . "'")->order('DIA_DATE desc')->select();
        }
        return $lists;
    }

    /*
     * 获取周报列表
     * param $limit 取几条，空取全部
     * return array
     */

    private function getWeeklyData($map, $limit = '') {
        $p = I('get.p', 1, 'intval');
        $start = $limit * ($p - 1);
        if ($limit) {
            $lists = M('weekly')->field("id,user_id,start_date,end_date")->where($map)->order('start_date desc')->limit($start, $limit)->select();
        } else {
            $lists = M('weekly')->field("id,user_id,start_date,end_date")->where($map)->order('start_date desc')->select();
        }
        return $lists;
    }

    //编辑人日志
    public function editDiary() {
        if (IS_AJAX) {
            $data = I('post.');
            //添加diary表
            $cdata['SUBJECT'] = $data['SUBJECT'];
            $cdata['CONTENT'] = $data['CONTENT'];
            $cdata['DIA_DATE'] = $data['DIA_DATE'] ? $data['DIA_DATE'] : date('Y-m-d');
            $cdata['DIA_TIME'] = date('Y-m-d H:i:s');
            $cdata['DIA_TYPE'] = $data['DIA_TYPE'];
            $cdata['TO_ID'] = implode(',', $data['undefined']);
            $res = M('diary')->where('DIA_ID = ' . $data['DIA_ID'])->save($cdata);
            if ($res) {
                $return['info'] = '编辑成功';
                $return['url'] = U('userLists');
            } else {
                $return['info'] = '编辑失败';
            }
            $this->ajaxReturn($return);
        }
        $dia_id = I('get.dia_id');
        $data = M('diary')->where('DIA_ID = ' . $dia_id)->find();
//        $tmp = explode(' ', $data['subject']);
//        array_pop($tmp);
//        $data['sub'] = implode(' ', $tmp);
//        $data['content'] = strip_tags($data['content']);
        $this->data = $data;
        $this->display();
    }

    //日志详情
    public function show() {
        $dia_id = I('id') ? I('id') : session('pcId');
        $map['DIA_ID'] = $dia_id;
        $info = M('diary')->field("DIA_ID,USER_ID,SUBJECT,CONTENT,DIA_DATE,READERS")->where($map)->find();
        
        
        if ($info) {
            
            //判断是否有回复评论的权限
            if($info['user_id'] == session('user_id')){
                $is_reply = 1;
                $is_del = 1;
                $this->is_reply = $is_reply;
            }
            
            //写入阅读人员if  修改时间2017-11-13 by qiaoshoujuan 
            if ($info['user_id'] != session('user_id')) {
                if (!strstr($info['readers'], session('user_id'))) {
                    if ($info['readers']) {
                        $rdata['READERS'] .= $info['readers'] . session('user_id') . ",";
                    } else {
                        $rdata['READERS'] .= session('user_id') . ",";
                    }
                }

                $r = M('diary')->where("DIA_ID = " . $dia_id)->save($rdata);
            }
            $info['dia_date'] = date("Y-m-d", strtotime($info['dia_date']));
            $readers = explode(',', $info['readers']);
            foreach ($readers as $key => $value) {
                $readers_str .= getChineseName($value) . ',';
            }
        }
        $info['readers'] = substr($readers_str, 0, -1);
        //查看评论
        $comments = M('diary_comment')->where("DIA_ID = " . $dia_id)->select();     
        foreach ($comments as $k => $v) {
            if($v['user_id'] == session('user_id') || $info['user_id'] == session('user_id')){
                $comments[$k]['is_del'] = 1;
            } 
            $comments[$k]['user_name'] = getChineseName($v['user_id']);
            $comments[$k]['content'] = strip_tags($v['content']);
            //查看回复
            $reply = M('diary_comment_reply')->field("REPLY_ID,REPLYER,REPLY_COMMENT,REPLY_TIME,COMMENT_ID,TO_ID")->where("COMMENT_ID = " . $v['comment_id'])->select();
            $comments[$k]['reply'] = $reply;
        }


        $this->comments = $comments;
        $this->diary = $info;
        $this->display();
    }

    //删除日志
    public function delDiary() {
        $diary_id = I('diary_id');
        $res = M('diary')->where('DIA_ID=' . $diary_id)->delete();
        if ($res) {
            $return['info'] = '删除成功';
        } else {
            $return['info'] = '删除失败';
        }
        $this->ajaxReturn($return);
    }

    //删除周报
    public function delWeekly() {
        $id = I('id');
        $res = M('weekly')->where('id=' . $id)->delete();
        if ($res) {
            $return['info'] = '删除成功';
        } else {
            $return['info'] = '删除失败';
        }
        $this->ajaxReturn($return);
    }

    //日志可查询用户
    public function userLists() {
        /* 查看当前用户的权限 
         * 0（管理员），1（董事长、总经理）可以查看所有

          $uMap['USER_ID'] = session('user_id');
          $userData = M('user')->field('USER_ID,DEPT_ID,DEPT_ID_OTHER,USER_PRIV,USER_PRIV_OTHER')->where($uMap)->find();
          $sql_1 = "select PRIV_NO from `user_priv` p,`user` u where u.USER_PRIV = p.USER_PRIV and u.USER_ID = '" . session("user_id") . "'";
          $privData = M()->query($sql_1);
          //当前用户是公司领导且不隶属于其他部门
          if ($userData['dept_id'] == 141 && $userData['dept_id_other'] == '') {
          //$user_id = "select USER_ID from user where USER_PRIV in(select USER_PRIV from `user_priv` where PRIV_NO > " . $privData[0]['priv_no'] . ")";
          $depts = M('department')->order('DEPT_ID')->select();
          //获取总经理、董事长user_priv
          $privs = M('user_priv')->where('PRIV_NO <= ' . $privData[0]['priv_no'])->getField('user_priv', true);
          if (!is_array($privs)) {
          $privs[] = $privs;
          }
          $userMap['USER_PRIV'] = array('not in', $privs);
          $lists = [];
          foreach ($depts as $k_dept => $v_dept) {
          $userMap['DEPT_ID'] = $v_dept['dept_id'];
          $lists[$k_dept]['dept_id'] = getDeptName($v_dept['dept_id']);
          $lists[$k_dept]['user_name'] = M('user')->field('USER_ID')->where($userMap)->select();
          }
          $this->lists = $lists;
          } else {
          if ($userData['dept_id'] == 141 && $userData['dept_id_other'] != '') {
          $user_id = "select USER_ID from user where USER_PRIV in(select USER_PRIV from `user_priv` where PRIV_NO > " . $privData[0]['priv_no'] . ") and DEPT_ID in (" . substr($userData["dept_id_other"], 0, -1) . ")";
          $id_arr = M()->query($user_id);
          } elseif ($userData['dept_id'] != 141) {
          if ($privData[0]['priv_no'] >= 40) {
          $id_arr = array(array('user_id' => session('user_id')));
          } else {
          $user_id = "select USER_ID from user where USER_PRIV in(select USER_PRIV from `user_priv` where PRIV_NO > " . $privData[0]['priv_no'] . ") and DEPT_ID = " . $userData["dept_id"];
          $id_arr = M()->query($user_id);
          }
          }

          //        $users = array_merge($id_self,$id_arr);
          foreach ($id_arr as $key => $value) {
          $id_arr[$key]['user_name'] = getChineseName($value['user_id']);
          }

          $this->userLists = $id_arr;
          }

          //        print_r($users);
          $this->display(); */
        $dept_id = I('id');
        if ($dept_id) {
            $map['DEPT_ID'] = I('id');
        } else {
            if (session('dept_id') == 141 && session('dept_id_other') != '') {
                $map['DEPT_ID'] = explode(',', session('dept_id_other'))[0];
            } else {
                $map['DEPT_ID'] = session('dept_id');
            }
            $data = M('user')->field('USER_ID,USER_NAME,USER_PRIV,DEPT_ID,DEPT_ID_OTHER,head')->where($map)->select();
            $this->dept = session('dept_id_other') ? getDeptName(explode(',', session('dept_id_other'))[0]) : getDeptName(session('dept_id'));
        }
        $data = M('user')->field('USER_ID,USER_NAME,USER_PRIV,DEPT_ID,DEPT_ID_OTHER,head')->where($map)->select();

        $this->userLists = $data;
        $this->display();
    }

    //日志查询
    public function search() {
        $user_id = I('get.user_id');
        $uMap['USER_ID'] = $user_id;
        $diaryData = M('diary')->order('DIA_DATE desc')->where($uMap)->limit(0, 10)->select();
        foreach ($diaryData as $key => $value) {
            if ($value['dia_date'] !== '0000-00-00') {
                $diaryData[$key]['dia_date'] = date('Y-m-d', strtotime($value['dia_date']));
            }
            $diaryData[$key]['user_name'] = getChineseName($value['user_id']);
            $diaryData[$key]['session_user'] = session("user_id");
        }
//        print_r($diaryData);
        $this->lists = $diaryData;
        $this->display();
    }

    //日志评论
    public function commentDiary() {
        $dia_id = I('get.dia_id');
        $data = M('diary')->field('DIA_ID,USER_ID,DIA_DATE,SUBJECT,CONTENT')->where('DIA_ID = ' . $dia_id)->find();
        $this->data = $data;
        $this->display();
    }

    //添加评论
    public function addComment() {
        if (IS_AJAX) {
            $data = I('post.');
            if (I('get.type') == 'weekly') {
                $data['content'] = $data['CONTENT'];
                $data['create_time'] = time();
                $data['user_id'] = session('user_id');
                $res = M('weekly_comment')->add($data);
                
                //添加提醒
                $row = M('weekly')->find($data['week_id']);
                $content = $row['title'].'的工作周报有一条领导批注，<a href="http://www.jsumt.com:88/index.php/Index/Diary/showWeekly/id/' . $row['id'] . '">点击查看</a>';
                setWeixinMsg($row['user_id'], $content);
            } else {
                //添加diarycomment表
                $cdata['USER_ID'] = session('user_id');
                $cdata['DIA_ID'] = $data['DIA_ID'];
                $cdata['CONTENT'] = $data['CONTENT'];
                $cdata['SEND_TIME'] = date('Y-m-d H:i:s');
                //添加提醒
                $map['DIA_ID'] = $data['DIA_ID'];
                $row = M('diary')->where($map)->find();
                $content = $row['subject'].'的工作日志有一条领导批注，<a href="http://www.jsumt.com:88/index.php/Index/Diary/show/dia_id/' . $row['dia_id'] . '">点击查看</a>';
                setWeixinMsg($row['user_id'], $content);

                $res = M('diary_comment')->add($cdata);
            }
            if ($res) {
                $return['info'] = '提交成功';
                if (I('type') == 'weekly') {
                    $return['url'] = U('search', array('user_id' => $data['user_to']));
                } else {
                    $return['url'] = U('search', array('user_id' => $data['user_to']));
                }
            } else {
                $return['info'] = '提交失败';
            }
            $this->ajaxReturn($return);
        }
        $this->display();
    }

    //回复日志评论
    public function replyDiary() {
        if (IS_AJAX) {
            $dia_id = I('get.dia_id');
            $content = I('get.content');
            $comment_id = I('get.comment_id');
            $comment_user = M("diary_comment")->where('COMMENT_ID = '.$comment_id)->getField('USER_ID');
            $rdata['REPLY_COMMENT'] = $content;
            $rdata['REPLY_TIME'] = date("Y-m-d H:i:s");
            $rdata['REPLYER'] = session('user_id');
            $rdata['COMMENT_ID'] = $comment_id;
            $rdata['TO_ID'] = $comment_user;
            $res = M('diary_comment_reply')->add($rdata);
            echo $url = "index.php/Index/Diary/show/dia_id/" . $dia_id . ".html";
        }
    }

    //下拉加载更多
    public function dropload($user_id) {
        $limit = $this->limit;
        $lists = $this->getDiaryData($limit, $user_id);
//        print_r($lists);die;
        foreach ($lists as $key => $row) {
            if ($row['dia_date'] !== '0000-00-00') {
                $lists[$key]['dia_date'] = date('Y-m-d', strtotime($row['dia_date']));
            }
            $lists[$key]['user_name'] = getChineseName($row['user_id']);
            $lists[$key]['session_user'] = session('user_id');
            //截取日志日期
            if (is_numeric(substr($row['subject'], 0, 4))) {
                $subdate = msubstr($row['subject'], 0, 10, 'utf-8', false);
            }
            $lists[$key]['dia_date'] = $subdate ? $subdate : date('Y-m-d', strtotime($row['dia_date']));
        }
        $this->ajaxReturn($lists);
    }

    //周报下拉
    public function droploadWeekly() {
        //$limit = $this->limit;
        $limit = 1;
        $map['user_id'] = I('user_id');
        $lists = $this->getWeeklyData($map, $limit);
        foreach ($lists as $key => $row) {
            $lists[$key]['user_name'] = getChineseName($row['user_id']);
            $lists[$key]['start_date'] = date('Y-m-d', $row['start_date']);
            $lists[$key]['end_date'] = date('m-d', $row['end_date']);
            $lists[$key]['current'] = session('user_id');
        }
        $this->ajaxReturn($lists);
    }

    //我的周报列表
    public function weeklyList() {
        if (I('id')) {
            $map['user_id'] = I('id');
        } else {
            $map['user_id'] = session('user_id');
        }
        //$limit = $this->limit;
        $limit = 1;
        $this->lists = $this->getWeeklyData($map, $limit);
        $this->user_id = $map['user_id'];
        $this->display();
    }

    //新建周报
    public function saveWeekly() {
        if (IS_AJAX) {
            $data = I('post.');
            $data['start_date'] = strtotime($data['start_date']);
            $data['end_date'] = strtotime($data['end_date']);
            if (strpos($data['title'], '(') === false) {
                $data['title'] = $data['title'] . ' (第' . date('W') . '周)';
            }
            $data['last_time'] = time();
            if($data['to_id']){
                $data['to_id'] = $data['dept_ids'] ? implode(',', $data['dept_ids']) : $data['to_id'];
            }
            
            if ($data['id']) {
                $res = M('weekly')->save($data);
            } else {
                $data['user_id'] = session('user_id');
                $data['dept_id'] = session('dept_id');
                $data['priv_id'] = session('user_priv');
                $data['create_time'] = time();
                $res = M('weekly')->add($data);
            }
            if ($res !== false) {
                $return['info'] = '提交成功';
                $return['url'] = U('weeklyList');
            } else {
                $return['info'] = '提交失败';
            }
            $this->ajaxReturn($return);
        }
        if (I('id')) {
            $this->info = M('weekly')->find(I('id'));

            //组成部门数组
            $this->depts = $this->info['to_id'] ? explode(',', $this->info['to_id']) : '';
        }
        $this->id = I('id') ? I('id') : 0;

        $this->display();
    }

    public function showWeekly() {
        $id = I('id');
        $info = M('weekly')->find($id);
        $comments = M('weekly_comment')->where('week_id=' . $id)->select();
        foreach ($comments as $key => $row) {
            $map['comment_id'] = $row['id'];
            $comments[$key]['reply'] = M('weekly_comment_reply')->where($map)->select();
        }
        $info['comments'] = $comments;

        //添加阅读者ID
        if ($info['user_id'] != session('user_id')) {
            if ($info['readers']) {
                if (strpos($info['readers'], session('user_id')) === false) {
                    $saveData['readers'] = $info['readers'] . ',' . session('user_id');
                } else {
                    $saveData['readers'] = $info['readers'];
                }
            } else {
                $saveData['readers'] = session('user_id');
            }
        }

        $map['id'] = $id;
        M('weekly')->where($map)->save($saveData);

        $this->info = $info;

        $this->display();
    }
    
    //日志查询（公司领导）
   public function diaryDeptLists() {
        $this->lists = M('department')->field('DEPT_ID,DEPT_NAME')->select();
        $this->display();
    }

    //周报查询
    public function weeklyUserLists() {
        $dept_id = I('id');
        if ($dept_id) {
            $map['DEPT_ID'] = I('id');
        } else {
            if (session('dept_id') == 141 && session('dept_id_other') != '') {
                $map['DEPT_ID'] = explode(',', session('dept_id_other'))[0];
            } else {
                $map['DEPT_ID'] = session('dept_id');
            }
            $data = M('user')->field('USER_ID,USER_NAME,USER_PRIV,DEPT_ID,DEPT_ID_OTHER,head')->where($map)->select();
            $this->dept = session('dept_id_other') ? getDeptName(explode(',', session('dept_id_other'))[0]) : getDeptName(session('dept_id'));
        }
        $data = M('user')->field('USER_ID,USER_NAME,USER_PRIV,DEPT_ID,DEPT_ID_OTHER,head')->where($map)->select();

        $this->lists = $data;
        $this->display();
    }

    //周报查询（公司领导）
    public function weeklyDeptLists() {
        $this->lists = M('department')->field('DEPT_ID,DEPT_NAME')->select();
        $this->display();
    }

    //回复评伦
    public function replyWeekly() {
        $data = I('post.');
        $data['user_id'] = session('user_id');
        $data['create_time'] = time();
        $res = M('weekly_comment_reply')->add($data);
        $return['status'] = $res ? 1 : 0;
        $this->ajaxReturn($return);
    }

    //周报评论
    public function commentWeekly() {
        $id = I('id');
        $this->info = M('weekly')->find($id);

        $this->display();
    }
    
    //删除日志回复
    public function delReply() {
        $reply_id = I('reply_id');
        $res = M('diary_comment_reply')->where('REPLY_ID=' . $reply_id)->delete();
        if ($res) {
            $return['info'] = '删除成功';
        } else {
            $return['info'] = '删除失败';
        }
        $this->ajaxReturn($return);
    }
    
    //删除日志评论同时回复
    public function delDiaryComment() {
        $comment_id = I('comment_id');
        $res = M('diary_comment')->where('COMMENT_ID=' . $comment_id)->delete();
        $res1 = M('diary_comment_reply')->where('COMMENT_ID=' . $comment_id)->delete();
        if ($res || $res1) {
            $return['info'] = '删除成功';
        } else {
            $return['info'] = '删除失败';
        }
        $this->ajaxReturn($return);
    }
}
